package controllers;

import com.google.gson.JsonObject;
import java.util.*;
import play.mvc.Controller;
import models.*;

/**
 * 
 * @author Maryam
 * 
 */
public class SignUp extends Controller {

	public static void signUp() {
		render();
	}

	/**
	 * A method that creates a new user
	 * 
	 * @author Maryam
	 * @param username
	 *            user's user name
	 * @param password
	 *            user's password
	 * @param fullName
	 *            user's full name
	 * @param eMail
	 *            user's email
	 * @param dateOfBirth
	 *            user's date of birth
	 * @param address
	 *            user's address
	 * @param mobile
	 *            user's mobile
	 */
	public static void addUser(String username, String password,
			String fullName, String eMail, String dateOfBirth, String address,
			String mobile) {

		long countUsername = IdeaDeveloper.count("username = ?", username);
		long countEmail = IdeaDeveloper.count("eMail = ?", eMail);

		JsonObject json = new JsonObject();

		if (countUsername != 0) {
			json.addProperty("output", "Sorry, this username is unavailable");
		} else {
			if (countEmail != 0) {
				json.addProperty("output", "Sorry, this email is unavailable");
			} else {

				IdeaDeveloper ideaDeveloper = new IdeaDeveloper();
				if (mobile.length() != 0) {
					int mobNum = Integer.parseInt(mobile);
					ideaDeveloper.mobileNumber = mobNum;
				}
				ideaDeveloper.username = username;
				ideaDeveloper.password = password;
				ideaDeveloper.fullName = fullName;
				ideaDeveloper.eMail = eMail;
				ideaDeveloper.dateOfBirth = dateOfBirth;
				ideaDeveloper.address = address;

				ideaDeveloper.save();
				Log log = new Log("^ joined the application.");
				log.ids = ideaDeveloper.id + "";
				log.types = "developer";
				log.save();
				json.addProperty("output", "Congratulations");
				IdeaDeveloper.sendEMail(eMail, "Megasoft Product",
						"Welcome to megasoft web application");
			}
		}
		renderJSON(json.toString());
	}

	/**
	 * this method checks if the username is being used by another user
	 * 
	 * @param username
	 *            the username that we will check on
	 */
	public static void instantUserName(String username) {
		JsonObject json = new JsonObject();
		json.addProperty("valid",
				IdeaDeveloper.count("username=?", username) == 0);
		renderJSON(json.toString());
	}

	/**
	 * this method checks if the email is being used by another user
	 * 
	 * @param email
	 *            the email that we will check on
	 */
	public static void instantEmail(String email) {
		JsonObject json = new JsonObject();
		json.addProperty("valid", IdeaDeveloper.count("eMail=?", email) == 0);
		renderJSON(json.toString());
	}
}
